﻿using FxSuperCore.Utils;
using Keystone;

namespace MemHack.Util
{
	public static class AsmUtil
	{
		/// <summary>
		/// 汇编转机器码
		/// </summary>
		/// <param name="arch">系统架构</param>
		/// <param name="mode">模式</param>
		/// <param name="syntax">语法格式</param>
		/// <param name="asm">汇编语句</param>
		/// <param name="addr">当前语句起始地址</param>
		/// <returns>机器码</returns>
		public static byte[] AsmToBytes(Architecture arch, Mode mode, OptionValue syntax, string asm, ulong addr)
		{
			using (Engine engine = new Engine(arch, mode){ThrowOnError = true})
			{
				engine.SetOption(OptionType.SYNTAX, (uint)syntax);
				engine.ResolveSymbol += (string symbol, ref ulong value) =>
				{
					CommonUtils.ShowErrorMsg($"undefine symbol: {symbol}");
					return false;
				};
				EncodedData encodedData = engine.Assemble(asm, addr);
				return encodedData.Buffer;
			}
		}
	}
}
